var ztree_user, ztree_area;
var userStatus = true, areaStatus = true; //默认正常状态， flase 置灰色
var isFirst = true; // 给叶节点加图标，只在第一次加载，避免图片重复

$(function () {
    $(".btn-add").on("click", addSave);
    $(".btn-delete").on("click", deleteSave);
    $(".btn-add-exclude").on("click", addExcludeSave);
    $(".btn-delete-exclude").on("click", deleteExcludeSave);
    $(".btn-reset").on("click", resetAllTree);
    $("#btnAreaSearch").on("click", areaSearch);
    $("#btnUserSearch").on("click", userSearch);

    initAllTree();

    // 初始化ztree高度
    initZtreeBox();

    $(window).resize(function (event) {
        // 初始化ztree高度
        initZtreeBox();
    });
});

/**
 * 初始化ztree高度
 */
function initZtreeBox() {
    var h = $('html').height(),
        bh = $(".oper-box").outerHeight(),
        t = $(".ztree").offset().top;
    h = h - bh - t - 31;
    $(".ztree").height(h);
}

function initAllTree() {
    var url = '/manage/auth/scope/allua';
    Base.ajax({
        url: url,
        success: function (data) {
            data = data.data;
            if (null != data.users) {
                userTreeData = data.users;
                initUser(userTreeData, userStatus);
            }
            if (null != data.areas) {
                areaTreeData = data.areas;
                initArea(areaTreeData, areaStatus);
            }
            isFirst = false;
        }
    });
}

function initUser(data, status) {
    var zNodes = data;
    if (isFirst) {
        for (var i = zNodes.length - 1; i >= 0; i--) {
            var z = zNodes[i];
            if (z.type == "user") {
                z.name = '<i class="iconfont icon-yonghu"></i> ' + z.name;
                z.name = z.name + " [" + z.id + "]";
            }else {
                z.nocheck = true;
            }
        }
        ;
    }

    var setting = {
        view: {
            showIcon: false,
            nameIsHTML: true,
            showTitle: false,
            showLine: false,
            fontCss: function (treeId, treeNode) {
                var o = {};
                if (treeNode.highlight) {
                    o = {
                        color: "red",
                        "font-weight": "bold"
                    };
                } else if (!status) {
                    o = {
                        color: "#bbb",
                        "font-weight": "bold"
                    };
                } else {
                    o = {
                        color: "#32b5cb",
                        "font-weight": "bold"
                    };
                }

                return o;
            }
        },
        check: {
            enable: true,
            chkboxType: {
                "Y": "",
                "N": ""
            }
        },
        data: {
            simpleData: {
                enable: true
            }
        },
        callback: {
            beforeClick: function (event, treeId, treeNode) {
                return false;
            }
        }
    };

    ztree_user = $.fn.zTree.init($("#userTree"), setting, zNodes);
}

function initArea(data, status) {
    var zNodes = data;
    if (isFirst) {
        for (var i = zNodes.length - 1; i >= 0; i--) {
            var z = zNodes[i];
            if (z.type == "area") {
                z.name = '<i class="iconfont icon-shejishi"></i> ' + z.name;
                z.name = z.name + " [" + z.id + "]";
            }
        }
    }
    var setting = {
        view: {
            showIcon: false,
            nameIsHTML: true,
            showTitle: false,
            showLine: false,
            fontCss: function (treeId, treeNode) {
                var o = {};
                if (treeNode.highlight) {
                    o = {
                        color: "red",
                        "font-weight": "bold"
                    };
                } else if (!status) {
                    o = {
                        color: "#bbb",
                        "font-weight": "bold"
                    };
                } else {
                    o = {
                        color: "#e89531",
                        "font-weight": "bold"
                    };
                }
                return o;
            }
        },
        check: {
            enable: true,
            chkboxType: {
                "Y": "",
                "N": ""
            }
        },
        data: {
            simpleData: {
                enable: true
            }
        },
        callback: {
            beforeClick: function (event, treeId, treeNode) {
                return false;
            }
        }
    };

    ztree_area = $.fn.zTree.init($("#areaTree"), setting, zNodes);
}

function addSave() {
    //查看模式不能保存
    if ($("#viewMode").prop("checked")) {
        return;
    }

    //判空
    var user_nodes = ztree_user.getCheckedNodes(true);
    var area_nodes = ztree_area.getCheckedNodes(true);
    //拼接参数
    var uId = [],
        uName = [],
        aId = [],
        aName = [];
    for (var i = user_nodes.length - 1; i >= 0; i--) {
        var u = user_nodes[i];
        if (u.type == "user") {
            uId.push(u.id);
            uName.push(u.name);
        }
    }

    for (var i = area_nodes.length - 1; i >= 0; i--) {
        var a = area_nodes[i];
        if (a.type == "area") {
            aId.push(a.id);
            aName.push(a.name);
        }
    }

    var countNull = 0;
    if (uId.length == 0) {
        countNull++;
    }
    if (aId.length == 0) {
        countNull++;
    }
    if (countNull > 1) {
        return;
    }

    uId = uId.join(";");
    uName = uName.join("　");
    aId = aId.join(";");
    aName = aName.join("　");

    var data = {
        "users": uId,
        "areas": aId
    };

    var cntStr = '确认是否保存以下数据权限：<br/>';
    cntStr += '<br/><label>保存用户与地区对应关系：</label><br/>';
    cntStr += uName + " <-----> " + aName + "<br/>";

    BootstrapDialog.confirm({
        title: '新增权限',
        message: cntStr,
        type: BootstrapDialog.TYPE_PRIMARY,
        closable: true,
        draggable: true,
        btnCancelLabel: '取消',
        btnOKLabel: '确定',
        btnOKClass: 'btn-primary',
        callback: function (result) {
            if (result) {
                addSubmit(data);
            } else {

            }
        }
    });
}

function addSubmit(data) {
    var url = '/manage/auth/scope/add';
    Base.ajax({
        url: url,
        data: data,
        loadingCommit: true,
        success: function (data) {
            if (data.code && data.data == 1) {
                tipsuccess("新增成功！");
            } else {
                tiperror("新增失败！");
            }
        }
    });
}


function deleteSave() {
    //查看模式不能保存
    if ($("#viewMode").prop("checked")) {
        return;
    }

    //判空
    var user_nodes = ztree_user.getCheckedNodes(true);
    var area_nodes = ztree_area.getCheckedNodes(true);
    //拼接参数
    var uId = [],
        uName = [],
        aId = [],
        aName = [];
    for (var i = user_nodes.length - 1; i >= 0; i--) {
        var u = user_nodes[i];
        if (u.type == "user") {
            uId.push(u.id);
            uName.push(u.name);
        }
    }

    for (var i = area_nodes.length - 1; i >= 0; i--) {
        var a = area_nodes[i];
        if (a.type == "area") {
            aId.push(a.id);
            aName.push(a.name);
        }
    }

    var countNull = 0;
    if (uId.length == 0) {
        countNull++;
    }
    if (aId.length == 0) {
        countNull++;
    }
    if (countNull > 1) {
        return;
    }

    uId = uId.join(";");
    uName = uName.join("　");
    aId = aId.join(";");
    aName = aName.join("　");

    var data = {
        "users": uId,
        "areas": aId
    };

    var cntStr = '确认是否删除以下数据权限：<br/>';
    cntStr += '<br/><label>删除用户与地区对应关系：</label><br/>';
    cntStr += uName + " <-----> " + aName + "<br/>";

    BootstrapDialog.confirm({
        title: '删除权限',
        message: cntStr,
        type: BootstrapDialog.TYPE_DANGER,
        closable: true,
        draggable: true,
        btnCancelLabel: '取消',
        btnOKLabel: '确定',
        btnOKClass: 'btn-danger',
        callback: function (result) {
            if (result) {
                deleteSubmit(data);
            } else {

            }
        }
    });
}

function deleteSubmit(data) {
    var url = '/manage/auth/scope/delete';
    Base.ajax({
        url: url,
        data: data,
        loadingCommit: true,
        success: function (data) {
            if (data.code && data.data == 1) {
                tipsuccess("删除成功！");
            } else {
                tiperror("删除失败！");
            }
        }
    });
}

function addExcludeSave() {
    //查看模式不能保存
    if ($("#viewMode").prop("checked")) {
        return;
    }

    //判空
    var user_nodes = ztree_user.getCheckedNodes(true);
    var area_nodes = ztree_area.getCheckedNodes(true);
    //拼接参数
    var uId = [],
        uName = [],
        aId = [],
        aName = [];
    for (var i = user_nodes.length - 1; i >= 0; i--) {
        var u = user_nodes[i];
        if (u.type == "user") {
            uId.push(u.id);
            uName.push(u.name);
        }
    }

    for (var i = area_nodes.length - 1; i >= 0; i--) {
        var a = area_nodes[i];
        if (a.type == "area") {
            aId.push(a.id);
            aName.push(a.name);
        }
    }

    var countNull = 0;
    if (uId.length == 0) {
        countNull++;
    }
    if (aId.length == 0) {
        countNull++;
    }
    if (countNull > 1) {
        return;
    }

    uId = uId.join(";");
    uName = uName.join("　");
    aId = aId.join(";");
    aName = aName.join("　");

    var data = {
        "users": uId,
        "areas": aId
    };

    var cntStr = '确认是否保存以下数据权限：<br/>';
    cntStr += '<br/><label>保存用户与地区对应关系：</label><br/>';
    cntStr += uName + " <-----> " + aName + "<br/>";

    BootstrapDialog.confirm({
        title: '新增权限',
        message: cntStr,
        type: BootstrapDialog.TYPE_PRIMARY,
        closable: true,
        draggable: true,
        btnCancelLabel: '取消',
        btnOKLabel: '确定',
        btnOKClass: 'btn-primary',
        callback: function (result) {
            if (result) {
                addExcludeSubmit(data);
            } else {

            }
        }
    });
}

function addExcludeSubmit(data) {
    var url = '/manage/auth/scopeexclude/add';
    Base.ajax({
        url: url,
        data: data,
        loadingCommit: true,
        success: function (data) {
            if (data.code && data.data == 1) {
                tipsuccess("新增成功！");
            } else {
                tiperror("新增失败！");
            }
        }
    });
}


function deleteExcludeSave() {
    //查看模式不能保存
    if ($("#viewMode").prop("checked")) {
        return;
    }

    //判空
    var user_nodes = ztree_user.getCheckedNodes(true);
    var area_nodes = ztree_area.getCheckedNodes(true);
    //拼接参数
    var uId = [],
        uName = [],
        aId = [],
        aName = [];
    for (var i = user_nodes.length - 1; i >= 0; i--) {
        var u = user_nodes[i];
        if (u.type == "user") {
            uId.push(u.id);
            uName.push(u.name);
        }
    }

    for (var i = area_nodes.length - 1; i >= 0; i--) {
        var a = area_nodes[i];
        if (a.type == "area") {
            aId.push(a.id);
            aName.push(a.name);
        }
    }

    var countNull = 0;
    if (uId.length == 0) {
        countNull++;
    }
    if (aId.length == 0) {
        countNull++;
    }
    if (countNull > 1) {
        return;
    }

    uId = uId.join(";");
    uName = uName.join("　");
    aId = aId.join(";");
    aName = aName.join("　");

    var data = {
        "users": uId,
        "areas": aId
    };

    var cntStr = '确认是否删除以下数据权限：<br/>';
    cntStr += '<br/><label>删除用户与地区对应关系：</label><br/>';
    cntStr += uName + " <-----> " + aName + "<br/>";

    BootstrapDialog.confirm({
        title: '删除权限',
        message: cntStr,
        type: BootstrapDialog.TYPE_DANGER,
        closable: true,
        draggable: true,
        btnCancelLabel: '取消',
        btnOKLabel: '确定',
        btnOKClass: 'btn-danger',
        callback: function (result) {
            if (result) {
                deleteExcludeSubmit(data);
            } else {

            }
        }
    });
}

function deleteExcludeSubmit(data) {
    var url = '/manage/auth/scopeexclude/delete';
    Base.ajax({
        url: url,
        data: data,
        loadingCommit: true,
        success: function (data) {
            if (data.code && data.data == 1) {
                tipsuccess("删除成功！");
            } else {
                tiperror("删除失败！");
            }
        }
    });
}

function resetAllTree() {
    userStatus = true;
    areaStatus = true;
    initUser(userTreeData, userStatus);
    initArea(areaTreeData, areaStatus);
}

function userSearch() {
    var s = $("#userSearchInput").val();
    s = $.trim(s);

    ztree_user.expandAll(true);

    if (s.length > 0) {
        var nodes = ztree_user.getNodesByFilter(function (node) {
            var id = node.id;
            var name = node.name;
            var type = node.type;
            return ((id.indexOf(s) != -1 || name.indexOf(s) != -1) && "user" == type);
        });
        var selNodes = [];
        for (var i = nodes.length - 1; i >= 0; i--) {
            var node = nodes[i];
            selNodes = selNodes.concat(node.getPath());
        }
        ztree_user.hideNodes(ztree_user.getNodes());
        ztree_user.showNodes(selNodes); // BUG，因为showNodes会显示所有兄弟节点，导致会显示非匹配的兄弟节点

    } else {
        ztree_user.showNodes(ztree_user.getNodes());
    }
}

function areaSearch() {
    var s = $("#areaSearchInput").val();
    s = $.trim(s);

    ztree_area.expandAll(true);

    if (s.length > 0) {
        var nodes = ztree_area.getNodesByFilter(function (node) {
            var id = node.id;
            var name = node.name;
            var type = node.type;
            return ((id.indexOf(s) != -1 || name.indexOf(s) != -1) && "area" == type);
        });
        var selNodes = [];
        for (var i = nodes.length - 1; i >= 0; i--) {
            var node = nodes[i];
            selNodes = selNodes.concat(node.getPath());
        }
        ztree_area.hideNodes(ztree_area.getNodes());
        ztree_area.showNodes(selNodes); // BUG，因为showNodes会显示所有兄弟节点，导致会显示非匹配的兄弟节点
    } else {
        ztree_area.showNodes(ztree_area.getNodes());
    }
}